<script setup lang="ts">
import { ref,onMounted, onUnmounted, watch } from 'vue'
import { ElNotification } from 'element-plus'
import { getStorageList, addStorageRecord, getMaterialOptions } from '@/axios/api/package-material/storage'
import useUserStore from '@/store/user'
import StorageForm from '@/components/package-material/StorageForm.vue'
//@ts-ignore
import { throttle } from 'lodash'

interface StorageRecord {
  storageNumber: string | null
  code: string
  type: string
  description: string
  unit: string
  quantity: number
  remark: string
  operator: string
  createTime: string
  storageType: string
}

interface MaterialOption {
  code: string
  type: string
  description: string
  currentStock: number
}

const formRef = ref<InstanceType<typeof StorageForm> | null>(null)
const dialogVisible = ref(false)
const searchInput = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref(window.innerHeight - 64 - 40 - 51 - 52 - 72 - 20 - 64)
const tableData = ref<StorageRecord[]>([])
const materialOptions = ref<MaterialOption[]>([])

// 获取列表数据
const fetchData = async () => {
  try {
    const params: any = {
      search: searchInput.value,
      storage_type: 'I',
      page: currentPage.value,
      page_size: pageSize.value
    }
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1]
    }
    const response = await getStorageList(params)
    
    // 直接使用返回的分页数据
    tableData.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('Error fetching data:', error)
    ElNotification({
      title: '错误',
      message: '获取数据失败',
      type: 'error',
    })
  }
}

// 获取包材选项
const fetchMaterialOptions = async () => {
  loading.value = true
  try {
    const response = await getMaterialOptions()
    materialOptions.value = response
      .map((item: MaterialOption) => ({
        ...item,
        currentStock: Number(item.currentStock)
      }))
  } catch (error) {
    console.error('Error fetching material options:', error)
    ElNotification({
      title: '错误',
      message: '获取包材列表失败',
      type: 'error',
    })
  } finally {
    loading.value = false
  }
}

const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleMaterialChange = (material: MaterialOption) => {
  console.log('Selected material:', material)
}

const handleQuantityChange = (value: number) => {
  console.log('Quantity changed:', value)
}

// 更新表格高度
const updateTableHeight = () => {
  tableHeight.value = window.innerHeight - 64 - 40 - 51 - 52 - 72 - 20 - 64
}

// 防抖处理的方法
const throttleHandleSearch = throttle(() => {
  currentPage.value = 1
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const throttleResetSearch = throttle(() => {
  searchInput.value = ''
  dateRange.value = null
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const throttleHandleAdd = throttle(async () => {
  dialogVisible.value = true
  await fetchMaterialOptions()
}, 1000, {
  leading: true,
  trailing: false
})

const throttleSubmitForm = throttle(async (formEl: InstanceType<typeof StorageForm> | null) => {
  if (!formEl) return
  try {
    const valid = await formEl.validate()
    if (valid) {
      loading.value = true
      const userStore = useUserStore()
      const response = await addStorageRecord({
        storage_type: 'I',
        storage_number: formEl.form.storageNumber,
        material_code: formEl.form.materialCode,
        quantity: formEl.form.quantity,
        remark: formEl.form.remark,
        operator: userStore.username
      })

      if (!response || response.code === undefined || response.code === 200) {
        ElNotification({
          title: '成功',
          message: '入库成功',
          type: 'success',
        })
        dialogVisible.value = false
        fetchData()
      } else {
        ElNotification({
          title: '错误',
          message: response.message || '入库失败',
          type: 'error',
        })
      }
    }
  } catch (error) {
    console.error('Error submitting form:', error)
    ElNotification({
      title: '错误',
      message: '入库失败',
      type: 'error',
    })
  } finally {
    loading.value = false
  }
}, 1000, {
  leading: true,
  trailing: false
})

const throttleHandleSizeChange = throttle((val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const throttleHandleCurrentChange = throttle((val: number) => {
  currentPage.value = val
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

// 监听窗口大小变化
onMounted(() => {
  fetchData()
  fetchMaterialOptions()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', updateTableHeight)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})

// 添加监听器
watch([searchInput, dateRange], () => {
  currentPage.value = 1
  fetchData()
}, { deep: true })
</script>

<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">包材入库</span>
          <el-button type="primary" @click="throttleHandleAdd" v-has="`btn_add_storage_in`">新增入库</el-button>
        </div>
      </template>

      <div class="toolbar">
        <div class="search-bar">
          <el-input
            v-model="searchInput"
            placeholder="请输入编码或入库单号搜索"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="date-picker">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="throttleHandleSearch"
          />
        </div>

        <div class="buttons">
          <el-button type="primary" @click="throttleHandleSearch">搜索</el-button>
          <el-button @click="throttleResetSearch">重置</el-button>
        </div>
      </div>

      <el-table 
        :data="tableData" 
        style="width: 100%" 
        border 
        stripe
        :height="tableHeight"
      >
        <el-table-column prop="storageNumber" label="入库单号" width="180" />
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="createTime" label="入库时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-') }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="throttleHandleSizeChange"
          @current-change="throttleHandleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      title="新增入库"
      width="500px"
      :close-on-click-modal="false"
      @closed="handleDialogClose"
    >
      <StorageForm
        ref="formRef"
        storage-type="I"
        :material-options="materialOptions"
        :loading="loading"
        @material-change="handleMaterialChange"
        @quantity-change="handleQuantityChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="throttleSubmitForm(formRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  background-color: var(--el-color-primary-light-9);
}

.buttons {
  display: flex;
  gap: 10px;
}
</style> 